﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace Eniux.Framework.Extensions.XamlHelper
{
    /// <summary>
    /// 非依赖属性绑定帮助类
    /// </summary>
    public class NoDependencyPropertyBindingHelper : FrameworkElement
    {
        #region Source

        /// <summary>
        /// 源
        /// </summary>
        public Object Source
        {
            get { return GetValue(NoDependencyPropertyBindingHelper.SourceProperty); }
            set { SetValue(NoDependencyPropertyBindingHelper.SourceProperty, value); }
        }
        public static readonly DependencyProperty SourceProperty =
          DependencyProperty.Register("Source", typeof(object), typeof(NoDependencyPropertyBindingHelper),
          new FrameworkPropertyMetadata()
          {
              BindsTwoWayByDefault = true,
              DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
          });

        #endregion

        #region Target 

        /// <summary>
        /// 目标
        /// </summary>
        public Object Target
        {
            get { return GetValue(NoDependencyPropertyBindingHelper.TargetProperty); }
            set { SetValue(NoDependencyPropertyBindingHelper.TargetProperty, value); }
        }

        public static readonly DependencyProperty TargetProperty =
          DependencyProperty.Register("Target", typeof(object), typeof(NoDependencyPropertyBindingHelper),
          new FrameworkPropertyMetadata()
          {
              BindsTwoWayByDefault = true,
              DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
          });

        #endregion

        #region 方法

        /// <summary>
        /// 重写方法
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property.Name == NoDependencyPropertyBindingHelper.SourceProperty.Name)
            {
                //no loop wanted
                if (!object.ReferenceEquals(Source, Target))
                    Target = Source;
            }
            else if (e.Property.Name == NoDependencyPropertyBindingHelper.TargetProperty.Name)
            {
                //no loop wanted
                if (!object.ReferenceEquals(Source, Target))
                    Source = Target;
            }
        } 

        #endregion
    }
}
